<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.username" clearable style="width: 200px;" :placeholder="$t('请输入交接人')"/>
      <el-select clearable v-model="listQuery.type" :placeholder='$t("请选择结算类型")'>
        <el-option :label='$t("日中结算")' :value='1'></el-option>
        <el-option :label='$t("下班结算")' :value='2'></el-option>
      </el-select>
      <el-cascader
          :placeholder="$t('请选择区域地址')"
          class="filter-item"
          v-model="listQuery.regionIds"
          :options="countrys"
          @active-item-change="handleItemChange"
          :props="props"
          clearable
          filterable
      ></el-cascader>
      <el-select v-if="!shop" v-model="listQuery.shopId" clearable :placeholder="$t('请选择门店')">
        <el-option v-for="item in shops" :value="item.id" :label="item.name"></el-option>
      </el-select>

      <el-date-picker

        v-model="listQuery.timeHorizon"
        value-format="yyyy-MM-dd hh:mm:ss"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="——"
        :start-placeholder='$t("开始日期")'
        :end-placeholder='$t("结束日期")'
        :picker-options="pickerOptions">
      </el-date-picker>

      <el-button type="info" plain1 icon="el-icon-search" @click="handleFilter">{{ $t('Search') }}</el-button>
      <el-button type="primary" icon="el-icon-setting" @click="openAmountDialog">
        {{ $t('设置相差金额') }}
      </el-button>
    </div>

    <div class="table-layout">
      <el-row>
        <el-col :span="4" class="table-cell-title">{{$t('总订单金额')}}</el-col>
        <el-col :span="4" class="table-cell-title">{{$t('实收总现金')}}</el-col>
        <el-col :span="4" class="table-cell-title">{{$t('收取总现金')}}</el-col>
        <el-col :span="4" class="table-cell-title">{{$t('找回总现金')}}</el-col>
        <el-col :span="4" class="table-cell-title">{{$t('退款总现金')}}</el-col>
        <el-col :span="4" class="table-cell-title">{{$t('相差总现金')}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalOrderAmount) }}</el-col>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalActualReceivedCash) }}</el-col>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalCollectedCash) }}</el-col>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalChangeGivenCash) }}</el-col>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalRefundedCash) }}</el-col>
        <el-col :span="4" class="table-cell">$ {{ NumberUtils.formatFixed2(cashSummary.totalCashDifference) }}</el-col>
      </el-row>
    </div>
    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit  show-summary :sum-text='$t("合计")'
      :header-cell-style="{background:'#eef1f6',color:'#606266',top:'5px'}"
              highlight-current-row>
      <el-table-column type="index" :index="getIndex" :label="$t('序号')" width="50"></el-table-column>
      <el-table-column type="expand" width="50" :label="$t('面额')">
        <template slot-scope="{row}">
          <el-row style="margin:3px;">
            <el-col :span="1">
              <el-tag style="width: 60px" effect="dark">{{ $t('面额') }}</el-tag>
            </el-col>
            <el-col :span="1">
              <el-tag style="width: 60px" effect="dark">{{ $t('数量') }}</el-tag>
            </el-col>
            <el-col :span="1">
              <el-tag style="width: 60px" type="warning" effect="dark">{{ $t('总额') }}</el-tag>
            </el-col>
          </el-row>
          <el-row v-for="(item, index) in row.denominationMap" :key="index" style="margin:3px;">
            <el-col :span="1">
              <el-tag style="width: 60px" effect="dark">{{ item.price }}<span style="float: right">$</span></el-tag>
            </el-col>
            <el-col :span="1">
              <el-tag style="width: 60px;text-align: center" effect="dark">{{ item.number }}</el-tag>
            </el-col>
            <el-col :span="1">
              <el-tag style="width: 60px;text-align: center" type="warning" effect="dark">{{ NumberUtils.formatFixed2(item.price * item.number) }}<span style="float: right">$</span></el-tag>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('交接人')" prop="username"/>
      <el-table-column align="center" :label="$t('门店')" prop="shopName"/>
      <el-table-column align="center" :label="$t('交接时间')" width="200" prop="addTime"/>
      <el-table-column align="center" :label="$t('订单金额')" prop="orderCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.orderCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('实收金额')" prop="actualCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.actualCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('收取金额')" prop="receiveCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.receiveCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('找回金额')" prop="change">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.change) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('初始金额')" prop="initialCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.initialCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('退款金额')" prop="refundCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.refundCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('钱箱预计金额')" prop="estimateCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.estimateCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('钱箱实际金额')" prop="deserveCash">
        <template slot-scope="scope">
          $ {{ NumberUtils.formatFixed2(scope.row.deserveCash) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('相差金额')" prop="differenceAmount">
        <template slot-scope="scope">
          $ -{{ NumberUtils.formatFixed2(scope.row.differenceAmount) }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('结算类型')" prop="type">
        <template slot-scope="scope">
          {{ scope.row.type === 1 ? $t('日中结算') : $t('下班结算') }}
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('Operate')" width="120" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          <i class="el-icon-setting"></i>
          {{ $t('Operate') }}
        </template>
        <template slot-scope="scope">
          <el-popover
            placement="right"
            trigger="click">
            <el-table v-loading="cashScheduleLoading" :data="cashScheduleList"  max-height="500" stripe>
              <el-table-column align="center" fixed type="index" :label="$t('排序')" width="50"></el-table-column>
              <el-table-column align="center" width="100" property="type" :label="$t('类型')">
                <template slot-scope="scope">
                  {{ cashTypeMap[scope.row.type] }}
                </template>
              </el-table-column>
              <el-table-column align="center" width="200" property="payTime" :label="$t('支付时间')"></el-table-column>
              <el-table-column align="center" width="200" property="deviceNo" :label="$t('设备编号')"></el-table-column>
              <el-table-column align="center" :label="$t('订单金额')" prop="orderCash">
                <template slot-scope="scope">
                    $ {{ NumberUtils.formatFixed2(scope.row.orderCash) }}
                </template>
              </el-table-column>
              <el-table-column align="center" :label="$t('收取')" prop="receiveCash">
                <template slot-scope="scope">
                     $ {{ NumberUtils.formatFixed2(scope.row.receiveCash) }}
                </template>
              </el-table-column>
              <el-table-column align="center" :label="$t('找零')" prop="change">
                <template slot-scope="scope">
                     $ {{ NumberUtils.formatFixed2(scope.row.change) }}
                </template>
              </el-table-column>
              <el-table-column align="center" :label="$t('退款')" prop="refundCash">
                <template slot-scope="scope">
                     $ {{ NumberUtils.formatFixed2(scope.row.refundCash) }}
                </template>
              </el-table-column>
              <el-table-column align="center" :label="$t('实收')" prop="actualCash">
                <template slot-scope="scope">
                     $ {{ NumberUtils.formatFixed2(scope.row.actualCash) }}
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="cashScheduleTotal>20" :total="cashScheduleTotal" :page.sync="cashScheduleQuery.page" :limit.sync="cashScheduleQuery.limit"
                        @pagination="handleDetail(scope.row)"/>
            <el-button slot="reference" icon="el-icon-view" v-permission="['GET /admin/p/store_handover_detail']" type="primary"
                       size="mini" @click="handleDetail(scope.row)">{{ $t('Details') }}
            </el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>2" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>


    <AmountDifferenceDialog ref="amountDialogRef" />
  </div>
</template>

<script>
import AmountDifferenceDialog from './components/AmountDifferenceDialog.vue'
import {allForPerm, settlementList} from '@/api/shop'
import {cashSettlements,cashDetails,cashSummary} from '@/api/cashSettlement'
import { listCountryRegion, listSubRegion  } from '@/api/region'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import store from '@/store'
import NumberUtils from "@/utils/numberUtils";
export default {
  name: "handoverList",
  components: {
    BackToTop, Pagination,AmountDifferenceDialog
  },
  data() {
    const cashTypeMap={
      1: this.$t('订单商品'),
      2: this.$t('礼物卡充值'),
      3: this.$t('余额充值'),
    }
    return {
      NumberUtils,
      pickerOptions: {
        shortcuts: [{
          text: this.$t('最近一周'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近一个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('最近三个月'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      // 当前店铺
      shop: store.state.user.shop,
      listLoading: true,
      total: 0,
      listQuery: {
        shopId: '',
        page: 1,
        limit: 20,
        // 交接用户
        username: undefined,
        type: undefined,
        timeHorizon: undefined
      },
      countrys:[],
      props: {
        value:'id',
        label: 'nameEn',
        children: 'children',
        checkStrictly: true
      },
      list: [],
      shops: [],
      cashScheduleList:[],
      cashScheduleQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        userId:undefined,
        deviceNo:undefined,
        lastCheck:undefined,
        addTime:undefined,
      },
      cashScheduleTotal: 0,
      cashTypeMap,
      cashScheduleLoading:false,
      cashSummary:{
        totalOrderAmount:0.00,
        totalActualReceivedCash:0.00,
        totalCollectedCash:0.00,
        totalChangeGivenCash:0.00,
        totalRefundedCash:0.00,
        totalCashDifference:0.00,
      },
    }
  },
  created() {
    this.getList()
    this.getCountrys()
    allForPerm().then(response => {
      this.shops = response.data.data.list
    })
  },
  methods: {
    getList() {
      if(this.listQuery.regionIds){
        this.listQuery.regionId = this.listQuery.regionIds[this.listQuery.regionIds.length-1]
      }
      cashSettlements(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })

      this.getCashSummary();
    },
    handleItemChange(val) {
      let step = val.length
      let query = {
        id: val[val.length-1],
        type: 1
      }
      listSubRegion(query).then(response=>{
        let result = this.findObject(this.countrys, val)
        response.data.data.list.forEach(child=>{
          if(step <= 1){
            result.children.push(this._.defaults(child,{children:[]}))
          }else{
            result.children.push(child)
          }
        })
      })
    },
    findObject(arr, ids){
      for(let i=0;i<=arr.length-1;i++){
        let obj = arr[i]
        if(ids.length == 1 && obj.id == ids[0]){
          return obj;
        }else if(obj.id == ids[0]){
          ids.shift()
          return this.findObject(obj.children, ids)
        }
      }
    },
    getCountrys(){
      listCountryRegion().then(response=>{
        this.countrys = response.data.data.list.map(function(country){
          return _.defaults(country,{children:[]})
        })
      })
    },
    getCashSummary(){
      cashSummary(this.listQuery)
          .then(response => {
            this.cashSummary = response.data.data
          })
          .catch(() => {

          })
    },
    handleFilter() {
      this.getList()
    },
    openAmountDialog() {
      this.$refs.amountDialogRef.open()
    },

    handleDetail(row) {
      this.cashScheduleLoading=true
      this.cashScheduleQuery.userId=row.userId
      this.cashScheduleQuery.shopId=row.shopId
      this.cashScheduleQuery.deviceNo=row.deviceNo
      this.cashScheduleQuery.lastCheck=row.lastCheck
      this.cashScheduleQuery.addTime=row.addTime
      cashDetails(this.cashScheduleQuery).then(res=>{
        this.cashScheduleList = res.data.data.list
        this.cashScheduleTotal = res.data.data.total
        this.cashScheduleLoading=false
      })
      .catch(() => {
        this.cashScheduleList = []
        this.cashScheduleTotal = 0
        this.cashScheduleLoading=false
      })
     /* let id = row.id
      let query = {
        id: row.id
      };
      this.$router.push({path: '/shop/handover/detail', query: query})*/
    },
    getIndex(index) {
      return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit;
    }
  }
}
</script>

<style scoped>
.table-layout {
  margin-top: 20px;
  border-left: 1px solid #DCDFE6;
  border-top: 1px solid #DCDFE6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  background: #F2F6FC;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>
